package org.mianshi.ali;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

public class 日志输出1sub {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 日志目录
        String logDirectoryPath = "/home/admin/logs/";
        String keyword = "Login";

        // 获取所有日志文件
        List<Path> logFiles = null;
        try {
            logFiles = Files.walk(Paths.get(logDirectoryPath))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".log"))
                    .collect(Collectors.toList());
        } catch (IOException e) {
            System.err.println("Error reading log files: " + e.getMessage());
            return;
        }

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<Map.Entry<String, Integer>>> futures = new ArrayList<>();

        // 提交任务，每个任务处理一个文件
        for (Path logFile : logFiles) {
            futures.add(executor.submit(() -> processLogFile(logFile, keyword)));
        }

        // 收集结果
        Map<String, Integer> resultMap = new HashMap<>();
        for (Future<Map.Entry<String, Integer>> future : futures) {
            Map.Entry<String, Integer> entry = future.get();
            resultMap.put(entry.getKey(), entry.getValue());
        }

        // 关闭线程池
        executor.shutdown();

        // 排序结果：按 value 降序，再按文件名字母顺序
        List<Map.Entry<String, Integer>> sortedResults = resultMap.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue, Comparator.reverseOrder())
                        .thenComparing(Map.Entry::getKey))
                .collect(Collectors.toList());

        // 输出结果
        sortedResults.forEach(entry ->
                System.out.println("File: " + entry.getKey() + ", Count: " + entry.getValue())
        );
    }

    // 处理单个日志文件，返回文件名和去重后 "Login" 的数量
    private static Map.Entry<String, Integer> processLogFile(Path logFile, String keyword) {
        try (BufferedReader reader = Files.newBufferedReader(logFile)) {
            // 读取文件内容并过滤包含 "Login" 的行
            Set<String> uniqueLoginLines = reader.lines()
                    .filter(line -> line.contains(keyword))
                    .collect(Collectors.toSet());

            // 返回文件名和去重后的行数
            return new AbstractMap.SimpleEntry<>(logFile.getFileName().toString(), uniqueLoginLines.size());
        } catch (IOException e) {
            System.err.println("Error processing file " + logFile + ": " + e.getMessage());
            return new AbstractMap.SimpleEntry<>(logFile.getFileName().toString(), 0);
        }
    }
}
